let fromId;
let fromName;
let toId = null;
let toName;
let websocket;

function onlineList(uid) {
    $.ajax({
        url: `/api/chat/chatroom/onlineList/${uid}`,
        dataType: "json",
        type: "GET",
        success: function (res) {
            let arr = res.data;
            let html = "";
            for(let i in arr){
                let obj = arr[i];
                let name =  obj.username;
                if(name !== fromName){
                    html += userSpan(obj.id, obj.username);
                }
            }
            $("#onlineList").html(html);
            $("#onlineNum").text(arr.length);
        }
    });
}

function userSpan(id, name) {
    return `<span id="user${id}" onclick="chooseUser(${id}, '${name}')">${name}</span><br />`;
}

function chooseUser(id, username) {
    toId = id;
    toName = username;
    $("#contentTitle").text(toName);
}

window.onbeforeunload = () => {
    websocket.onclose();
};

$(document).ready(function() {
    let user = getUser();
    fromId = user.id;
    fromName = user.username;
    onlineList(fromId);
    websocket = new WebSocket(`ws://47.106.148.18:8080/api/chat/socket/${fromId}`);
    websocket.onmessage = function (event) {
        let data = JSON.parse(event.data);
        let onlineNum = $("#onlineNum");
        if (data.code === 0) {
            $("#onlineList").append(userSpan(data.from, data.fromName));
            let lastNum = onlineNum.text();
            onlineNum.text(parseInt(lastNum) + 1);
            alert(data.fromName + "上线了");
        } else if (data.code === 2) {
            $(`#user${data.from}`).remove();
            let lastNum = onlineNum.text();
            onlineNum.text(parseInt(lastNum) - 1);
            alert(data.fromName + "下线了");
        } else {
            toId = data.from;
            toName = data.fromName;
            let now = getNowDateStr();
            $("#content").append(`<label style="color: bisque">${now}<br />${data.fromName}：&nbsp;${data.message}</label><br />`);
        }
    };
    $("#send").click(() => {
         if(!toId){
             alert("请选择聊天对象");
             return;
         }
         let msg = $("#msg");
         let data = {};
         data["from"] = fromId;
         data["to"] = toId;
         data["message"] = msg.val();
         websocket.send(JSON.stringify(data));
         let now = getNowDateStr();
         $("#content").append(`<label style="color: blue">${now}<br />我：&nbsp;${data.message}</label><br />`);
         msg.val('');
    });
});